﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Lookstone.Utility
{
	public static class StringTool
	{
		/// <summary>
		/// Used to generate a Url friendly string based on an initial value and optional max value
		/// </summary>
		/// <param name="value"></param>
		/// <param name="maxLength"></param>
		/// <returns></returns>
		public static string UrlFriendlyString(this string value, int? maxLength = null)
		{
			if (string.IsNullOrWhiteSpace(value))
				return string.Empty;

			string tmpValue = Regex.Replace(value.ToLower().Trim().Replace(@"'", string.Empty), @"[^\w]+", "-");

			if (maxLength.HasValue && tmpValue.Length > maxLength)
				return tmpValue.Substring(0, maxLength.Value);

			return tmpValue;
		}

		/// <summary>
		/// Given a string, truncate it to the maximum length and optionally append ellipses and allow partial words
		/// </summary>
		/// <param name="value"></param>
		/// <param name="maxLength"></param>
		/// <param name="appendEllipses"></param>
		/// <param name="allowPartialWords"></param>
		/// <returns></returns>
		public static string Truncate(this string value, int maxLength, bool appendEllipses = false, bool allowPartialWords = true)
		{
			if (string.IsNullOrWhiteSpace(value))
				return string.Empty;

			if (value.Length > maxLength)
			{
				string newVal = value.Substring(0, maxLength);

				if (!allowPartialWords)
					newVal = newVal.Substring(0, newVal.LastIndexOf(' '));

				return newVal + (appendEllipses ? "..." : string.Empty);
			}

			return value;
		}
	}
}
